package com.mingdao.lhy.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mingdao.lhy.biz.WishFillingBiz;
import com.mingdao.lhy.constant.Constant;
import com.mingdao.lhy.mapper.signup.SignUpStudentMapper2;
import com.mingdao.lhy.mapper.wish.MiddleSchoolMapper;
import com.mingdao.lhy.mapper.wish.PhotoMapper;
import com.mingdao.lhy.pojo.MiddleSchool;
import com.mingdao.lhy.pojo.Photo;
import com.mingdao.lhy.pojo.ResponseVo;
import com.mingdao.lhy.pojo.SignUpStudent;
import com.mingdao.lhy.pojo.page.ChangePassword;
import com.mingdao.lhy.pojo.signup.SignUpStudent2;
import com.mingdao.lhy.service.CityService;
import com.mingdao.lhy.service.ImportService;
import com.mingdao.lhy.service.JuniorService;

import sun.misc.BASE64Decoder;

@Controller
@RequestMapping("/junior")
public class WishJuniorController {

	private static Logger log = LoggerFactory.getLogger(WishJuniorController.class);

	@Value("${photopath}")
	private String photoPath;

	/**
	 * #报名起止时间
	 */
	@Value("${bmkssj}")
	private String bmkssj;

	@Value("${bmjssj}")
	private String bmjssj;

	@Autowired
	private WishFillingBiz wishFillingBiz;

	@Autowired
	private CityService cityService;
	@Autowired
	private MiddleSchoolMapper middleSchoolMapper;

	@Autowired
	private JuniorService juniorService;

	@Autowired
	private ImportService importService;

	@Autowired
	private SignUpStudentMapper2 signUpStudentMapper2;

	@Autowired
	private PhotoMapper photoMapper;

	@RequestMapping("")
	public String index() {
		return "loginJuniorHighSchool";
	}

	@RequestMapping("logout")
	public String logout() {
		HttpSession session = wishFillingBiz.getSession();
		if (null != session) {
			session.removeAttribute("junior");
		}

		return "loginJuniorHighSchool";
	}

	/**
	 * 初级中学登录验证页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/check", method = RequestMethod.POST)
	public String check(@ModelAttribute("junior") MiddleSchool junior, Model model) {

		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior2 = (MiddleSchool) session.getAttribute("junior");

		log.debug("进入【初级中学登录验证页面】");
		if (null == junior || null == junior.getByzxdm()) {
			log.error("没有收到有效的请求数据");
			model.addAttribute("result", "没有收到有效的请求数据");
			return "loginJuniorHighSchool";
		}
		/**
		 * 根据初级中学代码查询高中学校信息
		 */
		MiddleSchool juniorDb = new MiddleSchool();
		juniorDb = middleSchoolMapper.getOne(junior.getByzxdm());
		if (null == juniorDb) {
			log.error("没有找到指定的初级中学");
			model.addAttribute("result", "没有找到指定的初级中学");
			return "loginJuniorHighSchool";
		}

		/**
		 * 判断初级中学是否第一次登录（如果密码为空，或者和初级中学代码相同则是初次登录）
		 * 
		 * 如果是，跳转到修改密码界面，如果不是，则继续前进到操作选择页面
		 */
		String dbPassword = juniorDb.getPassword().trim();
		if (null == dbPassword
				|| (dbPassword.equals(juniorDb.getByzxdm()) && dbPassword.equals(junior.getPassword()))) {
			log.debug("初级中学初次登录 ，进入【密码修改页面】");
			model.addAttribute("junior", juniorDb);
			session.setAttribute("junior", juniorDb);
			return "junior/changePasswdJunior";
			// return "loginJuniorHighSchool";

		}

		String pwd = "";
		// 如果session不为空，取session密码判断，否则取页面传入密码判断
		if (null != junior2) {
			pwd = junior2.getPassword();
		} else {
			pwd = junior.getPassword();
		}

		// 验证是否找到对应的初级中学
		// 并且输入的密码是否和查找到的初级中学密码是否一致
		if (null != juniorDb.getPassword() && juniorDb.getPassword().equals(pwd)) {

			// 验证成功转到填报页面
			log.debug("验证【成功】");
			model.addAttribute("junior", juniorDb);
			session.setAttribute("junior", juniorDb);

			// 转到导航选择页面
			return "junior/juniorselect";
		} else {
			// 验证失败继续回到登录页面
			// Model model = new Model();
			log.debug("验证【失败】");
			model.addAttribute("result", "验证失败，学校代码或密码不正确");
			return "loginJuniorHighSchool";
		}

	}

	/**
	 * 跳转到修改密码页面
	 * 
	 * @param zkw
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/goChangePasswd", method = RequestMethod.POST)
	public String goChangePasswd(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			return "/loginJuniorHighSchool";
		}
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		model.addAttribute("junior", junior);
		return "/junior/changePasswdJunior";

	}

	/**
	 * 提交修改密码
	 * 
	 * @param changePassword
	 * @param junior
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/doChangePasswd", method = RequestMethod.POST)
	public String changePwd(@ModelAttribute(value = "changePassword") ChangePassword changePassword,
			@SessionAttribute MiddleSchool junior, Model model) {

		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			return "/loginJuniorHighSchool";
		}

		/**
		 * 判断传入的密码
		 */
		if (null == model || null == model.asMap() || null == model.asMap().get("changePassword")) {
			log.error("未取到前台返回的密码值 ");
			model.addAttribute("msg", "未取到前台返回的密码值");
			// model.addAttribute("student", student);
			return "/junior/changePasswdJunior";
		}

		ChangePassword cp = (ChangePassword) model.asMap().get("changePassword");
		if (null == cp.getOldPassword()) {
			log.error("必须输入原来的密码值 ");
			model.addAttribute("msg", "必须输入原来的密码值");
			return "/junior/check";
		}
		if (null == cp.getNewPasswordOne() || null == cp.getNewPasswordTwo()) {
			log.error("必须输入新的码值 ");
			model.addAttribute("msg", "必须输入新的码值");
			// model.addAttribute("student", student);
			return "/junior/changePasswdJunior";
		}

		String oldPassword = cp.getOldPassword();
		String newPasswordOne = cp.getNewPasswordOne();
		String newPasswordTwo = cp.getNewPasswordTwo();

		/**
		 * 如果输入的旧密码等于初级中学本来的旧密码才可以更换密码
		 */
		if (!oldPassword.isEmpty() && !junior.getPassword().isEmpty()) {
			if (oldPassword.equals(junior.getPassword())) {
				/**
				 * 两次输入密码要一致才有效
				 */
				if (newPasswordOne.equals(newPasswordTwo)) {
					junior.setPassword(newPasswordOne);
				} else {
					log.error("两次密码不符，请重新核对 ");
					model.addAttribute("msg", "两次密码不符，请重新核对 ");
					model.addAttribute("junior", junior);
					return "/junior/changePasswdJunior";
				}
			} else {
				log.error("原密码不符，请重新核对 ");
				model.addAttribute("msg", "原密码不符，请重新核对 ");
				model.addAttribute("junior", junior);
				return "/junior/changePasswdJunior";
			}
		}
		/**
		 * 修改密码
		 */
		int result = juniorService.changePassword(junior);
		if (1 == result) {
			log.debug("密码修改成功");
		} else {
			log.warn("密码修改失败");
			model.addAttribute("junior", junior);
			return "junior/changePasswdJunior";
		} /**
			 * 跳转到登录界面重新登录
			 */
		return "loginJuniorHighSchool";
	}

	@RequestMapping("showHighSchool")
	public String highSchoolWish(Model model) {

		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			return "redirect:/loginJuniorHighSchool";
		}
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		model.addAttribute("junior", junior);

		List<SignUpStudent> students = juniorService.getWishedStudentByByzxdmWishedHigh(junior.getByzxdm(), null);
		model.addAttribute("students", students);

		return "junior/JuniorManageHighSchool";
	}

	@RequestMapping("showMiddleSchool")
	public String middleShoolWish(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			return "redirect:/loginJuniorHighSchool";
		}
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		model.addAttribute("junior", junior);

		List<SignUpStudent> students = juniorService.getWishedStudentByByzxdmWishedMiddle(junior.getByzxdm(), null);
		model.addAttribute("students", students);

		return "junior/JuniorManageMidSchool";
	}

	@RequestMapping("showSignUpInfo")
	public String signUpInfo(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			return "redirect:/loginJuniorHighSchool";
		}
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		model.addAttribute("junior", junior);

		List<SignUpStudent> students = juniorService.getWishedStudentByByzxdmWishedMiddle(junior.getByzxdm(), null);
		model.addAttribute("students", students);

		return "junior/JuniorManageSignUpInfo";
	}

	@RequestMapping("doSelectSignUpInfoByCondition")
	public String selectSignUpInfoByCondition(Model model, @ModelAttribute("sfzh") String sfzh) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			return "redirect:/loginJuniorHighSchool";
		}
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		model.addAttribute("junior", junior);

		Map<String, String> map = new HashMap<String, String>();
		map.put("byzxdm", junior.getByzxdm());
		map.put("condition", sfzh);
		List<SignUpStudent2> students = signUpStudentMapper2.listByByzxdmAndCondition(map);

		model.addAttribute("students", students);

		return "junior/JuniorManageSignUpInfo";
	}

	@RequestMapping("doSelectStudentWishByBmhHigh")
	public String selectStudentWishByBmhHigh(@ModelAttribute("bmh") String bmh, @ModelAttribute("sele") String sele,
			Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初级中学未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			return "/loginJuniorHighSchool";
		}

		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("junior/JuniorManageHighSchool");
			// return vo;
		}

		if (null == bmh || bmh.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件报名号");
			vo.setUrl("junior/JuniorManageHighSchool");
			// return vo;
		}
		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		/**
		 * 未填志愿
		 */
		if ("1".equals(sele)) {
			students = juniorService.getWishedStudentByByzxdmNotWishedHigh(junior.getByzxdm(), bmh);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			students = juniorService.getWishedStudentByByzxdmWishedHigh(junior.getByzxdm(), bmh);
		}

		model.addAttribute("students", students);
		model.addAttribute("junior", junior);
		model.addAttribute("sele", sele);

		// vo.setCode("ok");
		// vo.setMessage("查询完成");
		vo.setUrl("/junior/JuniorManageHighSchool");

		return "/junior/JuniorManageHighSchool";
	}

	@RequestMapping("doSelectStudentWishByConditionHigh")
	public String selectStudentWishByConditionHigh(@ModelAttribute("sele") String sele, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		ResponseVo vo = new ResponseVo();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初级中学未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			return "/loginJuniorHighSchool";
		}
		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("/junior/JuniorManageHighSchool");
			// return vo;

		}

		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		/**
		 * 未填志愿
		 */
		if ("1".equals(sele)) {
			students = juniorService.getWishedStudentByByzxdmNotWishedHigh(junior.getByzxdm(), null);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			students = juniorService.getWishedStudentByByzxdmWishedHigh(junior.getByzxdm(), null);
		}

		model.addAttribute("students", students);
		model.addAttribute("junior", junior);
		model.addAttribute("sele", sele);

		// return vo;
		return "/junior/JuniorManageHighSchool";
	}

	@RequestMapping("doSelectStudentWishByBmhMiddle")
	public String selectStudentWishByBmhMiddle(@ModelAttribute("bmh") String bmh, @ModelAttribute("sele") String sele,
			Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初级中学未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			return "/loginJuniorHighSchool";
		}

		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("junior/JuniorManageMidSchool");
			// return vo;
		}

		if (null == bmh || bmh.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件报名号");
			vo.setUrl("junior/JuniorManageMidSchool");
			// return vo;
		}
		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		/**
		 * 未填志愿
		 */
		if ("1".equals(sele)) {
			students = juniorService.getWishedStudentByByzxdmNotWishedMiddle(junior.getByzxdm(), bmh);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			students = juniorService.getWishedStudentByByzxdmWishedMiddle(junior.getByzxdm(), bmh);
		}

		model.addAttribute("students", students);
		model.addAttribute("junior", junior);
		model.addAttribute("sele", sele);

		// vo.setCode("ok");
		// vo.setMessage("查询完成");
		vo.setUrl("/junior/JuniorManageMidSchool");

		return "/junior/JuniorManageMidSchool";
	}

	@RequestMapping("doSelectStudentWishByConditionMiddle")
	public String selectStudentWishByConditionMiddle(@ModelAttribute("sele") String sele, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		ResponseVo vo = new ResponseVo();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初级中学未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			return "/loginJuniorHighSchool";
		}
		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("/junior/JuniorManageMidSchool");
			// return vo;

		}

		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		/**
		 * 未填志愿
		 */
		if ("1".equals(sele)) {
			students = juniorService.getWishedStudentByByzxdmNotWishedMiddle(junior.getByzxdm(), null);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			students = juniorService.getWishedStudentByByzxdmWishedMiddle(junior.getByzxdm(), null);
		}

		model.addAttribute("students", students);
		model.addAttribute("junior", junior);
		model.addAttribute("sele", sele);

		// return vo;
		return "/junior/JuniorManageMidSchool";
	}

	@RequestMapping("forgetPwd")
	public String forgetPwd() {
		return "junior/CountyEnrolStudent";
	}

	/**
	 * 选择学籍文件
	 * 
	 */
	@RequestMapping("selectExcel")
	public String selectExcel(Model model, HttpServletResponse response) {



		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			return "redirect:/loginJuniorHighSchool";
		}
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		model.addAttribute("junior", junior);
		/**
		 * 报名时间判断
		 */
		Date day = new Date();

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			response.setCharacterEncoding("UTF-8");

			Date now = df.parse(df.format(day)); // 当前时间
			Date startTime = df.parse(bmkssj);
			Date endTime = df.parse(bmjssj); // 截止时间
			if (now.before(endTime) && now.after(startTime)) {
				// 继续正常处理
				System.out.println("继续正常处理");

			} else {
				model.addAttribute("message", "非报名时间，不能导入");
				response.getWriter().write("<script>alert('非报名时间，不能导入');</script>");
				return "junior/juniorselect";
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			return "junior/juniorselect";
		}
		
		return "junior/upload";
	}

	/**
	 * 导入学籍文件到数据库
	 * 
	 * @param fileName 学籍文件名
	 * @param startRow 学籍数据起始行号
	 * 
	 */
	@RequestMapping("importStatus")
	@ResponseBody
	public String importStatus(HttpServletResponse response, @RequestParam("fileName") String fileName,
			@RequestParam("startRow") int startRow, Model model) {

		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			try {
				response.sendRedirect("/loginJuniorHighSchool");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// return "redirect:/loginJuniorHighSchool";
		}
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		model.addAttribute("junior", junior);

		try {
			// 取上传文件保存路径
			String uploadPath = ResourceUtils.getURL("classpath:").getPath() + "upload/" + junior.getByzxdm() + "/";
			List<String> errorList = importService.importStatus(uploadPath + fileName, startRow, junior.getByzxdm());
			if (null == errorList || errorList.size() == 0) {
				model.addAttribute("msg", "ok1");
				return "ok1";
				// return "junior/upload.html";
			} else {
				// return errorList;
				model.addAttribute("msg", errorList);
				return "error1";
				// return "junior/upload.html";
			}
			// return "junior/upload";

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return "error1";
			// return "junior/upload.html";
		}
		// return "junior/upload";

	}

	/**
	 * 上传文件至服务器
	 * 
	 * @param file
	 * @param model
	 * @return
	 */
	@RequestMapping("doUpload")
	@ResponseBody
	public String fileUpload(@RequestParam(value = "file", required = false) MultipartFile file, Model model) {

		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			return "redirect:/loginJuniorHighSchool";
		}
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		model.addAttribute("junior", junior);

		if (file.isEmpty()) {
			return "error";
		}
		String fileName = file.getOriginalFilename();
		String filePath;
		try {
			filePath = ResourceUtils.getURL("classpath:").getPath() + "upload/" + junior.getByzxdm() + "/";

			// 先判断文件夹路径是否存在，不存在则先创建
			File dir = new File(filePath);
			if (!dir.exists()) {
				dir.mkdirs();
			}

			File destFile = new File(filePath + fileName);
			file.transferTo(destFile);

			// 取上传文件保存路径
			// String uploadPath = ResourceUtils.getURL("classpath:").getPath() + "upload/"
			// + junior.getByzxdm() + "/";
			List<String> errorList = importService.importStatus(filePath + fileName, 2, junior.getByzxdm());
			if (null == errorList || errorList.size() == 0) {
				model.addAttribute("msg", "ok");
				return "ok";
				// return "junior/upload.html";
			} else {
				// return errorList;
				model.addAttribute("msg", errorList);
				return errorList.toString();
				// return "junior/upload.html";
			}

			// return "ok";
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "error";
	}

	/**
	 * 根据毕业中学代码查询所有已经报名的学生信息
	 * 
	 * @param byzxdm
	 * @param model
	 * @return
	 */
	@RequestMapping("doSelectSignUpStudentByByzxdm")
	public String selectSignUpStudentByByzxdm(Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初级中学未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			return "/loginJuniorHighSchool";
		}

//		if (null == byzxdm || byzxdm.isEmpty()) {
//			vo.setCode("stay");
//			vo.setMessage("未收到查询条件毕业中学代码");
//			vo.setUrl("junior/JuniorManageSignUpInfo");
//			// return vo;
//		}
		List<SignUpStudent2> students = new ArrayList<SignUpStudent2>();

		students = juniorService.findAllSignUpStudentsByByzxdm(junior.getByzxdm());
		model.addAttribute("students", students);
		model.addAttribute("junior", junior);

		// vo.setCode("ok");
		// vo.setMessage("查询完成");
		// vo.setUrl("/junior/JuniorManageSignUpInfo");

		return "/junior/JuniorManageSignUpInfo";
	}

	/**
	 * 查询待处理状态的已报名学生信息
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("doSelectSignUpStudentByDclzt")
	// @ResponseBody
	public String selectSignUpStudentByDclzt(Model model, HttpServletResponse response) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初级中学未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			return "/loginJuniorHighSchool";
		}
		model.addAttribute("junior", junior);
		
		/**
		 * 报名时间判断
		 */
		Date day = new Date();

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			response.setCharacterEncoding("UTF-8");

			Date now = df.parse(df.format(day)); // 当前时间
			Date startTime = df.parse(bmkssj);
			Date endTime = df.parse(bmjssj); // 截止时间
			if (now.before(endTime) && now.after(startTime)) {
				// 继续正常处理
				System.out.println("继续正常处理");

			} else {
				model.addAttribute("message", "非报名时间，不能转入转出");
				response.getWriter().write("<script>alert('非报名时间，不能转入转出');</script>");
				return "junior/juniorselect";
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			return "junior/juniorselect";
		}
		
		// 右边查询报名库中所属中学的所有已报名学生
		List<SignUpStudent2> studentLeft = new ArrayList<SignUpStudent2>();
		studentLeft = juniorService.findAllSignUpStudentsByByzxdm(junior.getByzxdm());

		List<SignUpStudent2> studentRight = new ArrayList<SignUpStudent2>();

		// 右边查询待处理状态的报名学生信息固定传2，保持和数据库定义一致
		studentRight = juniorService.findAllSignUpStudentsByDclzt("2");

		model.addAttribute("studentLefts", studentLeft);
		model.addAttribute("studentRights", studentRight);

		model.addAttribute("junior", junior);

		return "/junior/zhuanczhuanr";

		// return studentLeft;
	}

	/**
	 * 查询毕业中学所属已报名学生信息
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("doSelectSignUpStudentLeft")
	@ResponseBody
	public List<SignUpStudent2> selectSignUpStudentLeft(Model model, @RequestParam("sfzh") String sfzh) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初级中学未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			// return "/loginJuniorHighSchool";
		}

		// 右边查询报名库中所属中学的所有已报名学生
		List<SignUpStudent2> students = new ArrayList<SignUpStudent2>();
		Map<String, String> param = new HashMap<String, String>();
		param.put("byzxdm", junior.getByzxdm());
		param.put("sfzh", sfzh);
		students = signUpStudentMapper2.listByByzxdmAndSfzh(param);

		model.addAttribute("studentLefts", students);

		model.addAttribute("junior", junior);

		// return "/junior/zhuanczhuanr";

		return students;
	}

	/**
	 * 查询待处理状态的已报名学生信息
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("doSelectSignUpStudentRight")
	@ResponseBody
	public List<SignUpStudent2> selectSignUpStudentRight(Model model, @RequestParam("sfzh") String sfzh) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初级中学未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			// return "/loginJuniorHighSchool";
		}

		List<SignUpStudent2> students = new ArrayList<SignUpStudent2>();

		// 右边查询待处理状态的报名学生信息固定传2，保持和数据库定义一致
		Map<String, String> param = new HashMap<String, String>();
		param.put("dclzt", "2");
		param.put("sfzh", sfzh);
		students = signUpStudentMapper2.listByDclztAndSfzh(param);

		model.addAttribute("studentRight", students);

		model.addAttribute("junior", junior);

		// return "/junior/zhuanczhuanr";
		return students;
	}

	/**
	 * 提交更新报名或待处理状态学生信息
	 * 
	 * @param students
	 * @param model
	 * @param dclzt
	 * @return
	 */
	@RequestMapping("doUpdateDclzt")
	@ResponseBody
	public String updateDclzt(Model model, @RequestBody SignUpStudent2[] students
	// , @RequestParam("dclzt") String dclzt
	) {
		// ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			// vo.setCode("error");
			// vo.setMessage("初级中学未登录，请重新登录");
			// vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			return "loginJuniorHighSchool";
		}
		List<SignUpStudent2> ss = new ArrayList<SignUpStudent2>();
		ObjectMapper mapper = new ObjectMapper();

//		List<SignUpStudent2> studentsList = new ArrayList<SignUpStudent2>(students.length);
//		//	将数组转换为List
//		Collections.addAll(studentsList, students);

		List<SignUpStudent2> confirmList = new ArrayList<SignUpStudent2>();
		List<SignUpStudent2> dclList = new ArrayList<SignUpStudent2>();
		// 处理数据
		for (int i = 0; i < students.length; i++) {
			SignUpStudent2 tmpStu = students[i];
			tmpStu.setByzxdm(junior.getByzxdm());
			tmpStu.setByzxmc(junior.getByzxmc());
			if ("1".equals(students[i].getDclzt())) {
				// 修改转入后学生就读地
				tmpStu.setJdd(Constant.xsdm2jdd.get(junior.getByzxdm().substring(0, 4)));
				confirmList.add(tmpStu);
			} else if ("2".equals(students[i].getDclzt())) {
				dclList.add(tmpStu);
			}
		}
		int count = 0;
		count += juniorService.setConfirmBySfzh(confirmList);
		count += juniorService.setDclztBySfzh(dclList);
		if (count > 0)
			return "保存成功";
		return "保存失败";

		// 更新待处理状态为确定状态
//		if ("1".equals(dclzt)) {
//			juniorService.setConfirmBySfzh(students);
//		} else if ("2".equals(dclzt)) {
//			// 更新待处理状态为待处理状态
//			juniorService.setDclztBySfzh(students);
//		} else {
//			// 不正确的状态
//			log.warn("传入了不正确的待处理状态，未做更新");
//		}

//		model.addAttribute("students", students);
		// model.addAttribute("junior", junior);

		// return "/junior/zhuanczhuanr";
	}

	/**
	 * 查询未报名的学生信息
	 * 
	 * @param byzxdm
	 * @param model
	 * @return
	 */
	@RequestMapping("doSelectNotSignUpStudentByByzxdm")
	public String selectNotSignUpStudentByByzxdm(Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初级中学未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			return "/loginJuniorHighSchool";
		}

		List<SignUpStudent2> students = new ArrayList<SignUpStudent2>();
		// List<XueJi>
		// xueJes=juniorService.findNotSignUpStudentsByByzxdm(junior.getByzxdm());

		students = juniorService.findNotSignUpStudentsByByzxdm(junior.getByzxdm());

		model.addAttribute("students", students);
		model.addAttribute("junior", junior);

		return "/junior/JuniorManageSignUpInfo";
	}

	/**
	 * 根据学校代码和学生身份证号更新报名学生待处理状态为（待处理）
	 * 
	 * @param sfzhs
	 * @param model
	 * @return
	 */
	@RequestMapping("doSetSignUpStudentDclztBySfzhAndByzxdm")
	public String setSignUpStudentDclztBySfzhAndByzxdm(@RequestParam("sfzhs") List<String> sfzhs, Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初级中学未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			return "/loginJuniorHighSchool";
		}

		// 判断传入参数身份证号列表是否为空，是则返回不处理
		if (null == sfzhs || sfzhs.size() <= 0) {
			return "/junior/JuniorManageSignUpInfo";
		}

		List<SignUpStudent2> signUpStudents = new ArrayList<SignUpStudent2>();
		for (String s2 : sfzhs) {
			SignUpStudent2 student = new SignUpStudent2();

			student.setByzxdm(junior.getByzxdm());
			student.setByzxmc(junior.getByzxmc());
			student.setSfzh(s2);
			signUpStudents.add(student);
		}

		/**
		 * 将传入的指定身份证号学生待处理状态设置为（待处理）
		 */
		int result = juniorService.setDclztBySfzh(signUpStudents);

		if (result != sfzhs.size()) {
			log.error("传入学生数与实际更新学生数量不等，请仔细检查！");
		}

		model.addAttribute("students", signUpStudents);
		model.addAttribute("junior", junior);

		return "/junior/JuniorManageSignUpInfo";
	}

	/**
	 * 根据学校代码和学生身份证号更新报名学生待处理状态为（已确定）
	 * 
	 * @param sfzhs
	 * @param model
	 * @return
	 */
	@RequestMapping("doSetSignUpStudentConfirmBySfzhAndByzxdm")
	public String setSignUpStudentConfirmBySfzhAndByzxdm(@RequestParam("sfzhs") List<String> sfzhs, Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初级中学未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			return "/loginJuniorHighSchool";
		}

		// 判断传入参数身份证号列表是否为空，是则返回不处理
		if (null == sfzhs || sfzhs.size() <= 0) {
			return "/junior/JuniorManageSignUpInfo";
		}

		List<SignUpStudent2> signUpStudents = new ArrayList<SignUpStudent2>();
		for (String s2 : sfzhs) {
			SignUpStudent2 student = new SignUpStudent2();

			student.setByzxdm(junior.getByzxdm());
			student.setByzxmc(junior.getByzxmc());
			student.setSfzh(s2);
			signUpStudents.add(student);
		}

		/**
		 * 将传入的指定身份证号学生待处理状态设置为（已确定）
		 */
		int result = juniorService.setConfirmBySfzh(signUpStudents);

		if (result != sfzhs.size()) {
			log.error("传入学生数与实际更新学生数量不等，请仔细检查！");
		}

		model.addAttribute("students", signUpStudents);
		model.addAttribute("junior", junior);

		return "/junior/JuniorManageSignUpInfo";
	}

	@RequestMapping("addStudent")
	public String addStudent(Model model, HttpServletResponse response) {
		// 此页面和juniorAddStudent.html重复了？
		// return "junior/StudentEnrolmentInfo";
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			return "redirect:/loginJuniorHighSchool";
		}
		model.addAttribute("junior", junior);
		
		/**
		 * 报名时间判断
		 */
		Date day = new Date();

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			response.setCharacterEncoding("UTF-8");

			Date now = df.parse(df.format(day)); // 当前时间
			Date startTime = df.parse(bmkssj);
			Date endTime = df.parse(bmjssj); // 截止时间
			if (now.before(endTime) && now.after(startTime)) {
				// 继续正常处理
				System.out.println("继续正常处理");

			} else {
				model.addAttribute("message", "非报名时间，不能添加学生");
				response.getWriter().write("<script>alert('非报名时间，不能添加学生');</script>");
				return "junior/juniorselect";
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			return "junior/juniorselect";
		}
		
		return "junior/juniorAddStudent";
	}

	@RequestMapping(value = "doSaveSignUpStudent", method = RequestMethod.POST)
	public String doSaveSignUpStudent(SignUpStudent2 student, HttpServletResponse response, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			return "redirect:/loginJuniorHighSchool";
		}
		model.addAttribute("junior", junior);

		try {

			// student.setWbxh((signUpStudentMapper2.getMaxWbxh() + 1) + "");

			int count = -1;
			String retStr = "";
			// 先查询是否存在，存在则更新，不存在则插入
			SignUpStudent2 s2 = signUpStudentMapper2.getOne(student.getSfzh());
			if (null == s2) {
				student.setPassword(student.getSfzh().substring(10, 18));
				student.setDclzt("1");
				String xsdm = student.getByzxdm().substring(0, 4);
				student.setJdd(Constant.xsdm2jdd.get(xsdm));
				count = cityService.doSaveStudnet(student);
				if (count > 0) {
					retStr = "<script>alert('添加成功');</script>";
				} else {
					retStr = "<script>alert('添加失败');</script>";
				}
			} else {
				count = signUpStudentMapper2.updateByPrimaryKeySelective(student);
				if (count > 0) {
					retStr = "<script>alert('更新成功');</script>";
				} else {
					retStr = "<script>alert('更新失败');</script>";
				}
			}

			// response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");

			response.getWriter().write(retStr);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		SignUpStudent2 dbStudent = new SignUpStudent2();
		dbStudent = signUpStudentMapper2.getOne(student.getSfzh());
		model.addAttribute("junior", junior);
		model.addAttribute("stu", dbStudent);

		return "junior/updateStudent";
		// return "junior/JuniorManageSignUpInfo";
	}

	@RequestMapping(value = "doJuniorAddSignUpStudent", method = RequestMethod.POST)
	public String juniorAddSignUpStudent(SignUpStudent2 student, HttpServletResponse response, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			return "redirect:/loginJuniorHighSchool";
		}
		model.addAttribute("junior", junior);

		try {

			// student.setWbxh((signUpStudentMapper2.getMaxWbxh() + 1) + "");

			int count = -1;
			String retStr = "";
			// 先查询是否存在，存在则提示已报名，不存在则插入
			SignUpStudent2 s2 = signUpStudentMapper2.getOne(student.getSfzh());
			if (null == s2) {
				student.setPassword(student.getSfzh().substring(10, 18));
				student.setDclzt("1");
				String xsdm = student.getByzxdm().substring(0, 4);
				student.setJdd(Constant.xsdm2jdd.get(xsdm));
				count = cityService.doSaveStudnet(student);
				if (count > 0) {
					retStr = "<script>alert('添加成功');</script>";
				} else {
					retStr = "<script>alert('添加失败');</script>";
				}
			} else {

				retStr = "<script>alert('该生已报名，请到原学校办理手续');</script>";

			}

			// response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");

			response.getWriter().write(retStr);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		SignUpStudent2 dbStudent = new SignUpStudent2();
		dbStudent = signUpStudentMapper2.getOne(student.getSfzh());
		model.addAttribute("junior", junior);
		model.addAttribute("stu", dbStudent);

		// return "junior/updateStudent";
		return "junior/juniorAddStudent";
	}

	/**
	 * 跳转到修改学生信息页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "updateStudents", method = RequestMethod.POST)
	public String updateStudents(@ModelAttribute("signUpStudent") SignUpStudent2 signUpStudent, Model model,
			HttpServletResponse response) {
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "loginJuniorHigSchool";
		}
		model.addAttribute("junior", junior);
		model.addAttribute("stu", signUpStudent);
		
		/**
		 * 报名时间判断
		 */
		Date day = new Date();

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			response.setCharacterEncoding("UTF-8");

			Date now = df.parse(df.format(day)); // 当前时间
			Date startTime = df.parse(bmkssj);
			Date endTime = df.parse(bmjssj); // 截止时间
			if (now.before(endTime) && now.after(startTime)) {
				// 继续正常处理
				System.out.println("继续正常处理");

			} else {
				model.addAttribute("message", "非报名时间，不能修改");
				response.getWriter().write("<script>alert('非报名时间，不能修改');</script>");
				return "junior/juniorselect";
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			return "junior/juniorselect";
		}
		
		
		return "junior/updateStudent";
	}

	/**
	 * 
	 * @param response
	 */
	@RequestMapping(value = "doFileDownload", method = RequestMethod.POST)
	public void fileDownload(HttpServletResponse response) {
		// 得到ClassLoader 先得到Class,在得到ClassLoader
		ClassLoader c1 = this.getClass().getClassLoader();
		// 调用其getResourceAsStream，得到一个InputStream
		URL url = c1.getResource("xjmb.xls");
		String path = url.getPath();

		// 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
		response.setContentType("multipart/form-data");
		// 2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
		response.setHeader("Content-Disposition", "attachment;fileName=" + "xjmb.xls");
		ServletOutputStream out;
		// 通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
		File file = new File(path);

		try {
			FileInputStream inputStream = new FileInputStream(file);

			// 3.通过response获取ServletOutputStream对象(out)
			out = response.getOutputStream();

			int b = 0;
			byte[] buffer = new byte[512];
			while (b != -1) {
				b = inputStream.read(buffer);
				// 4.写到输出流(out)中
				out.write(buffer, 0, b);
			}
			inputStream.close();
			out.close();
			out.flush();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化学生密码，一次只能初始化一个学生
	 * 
	 * @param bmh
	 * @return
	 */
	@RequestMapping(value = "doInitPassword", method = RequestMethod.POST)
	// @ResponseBody
	public String initPassword(@ModelAttribute("sfzh") String sfzh, Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("junior")) {
			session = null;
			log.error("初中学校未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初中学校未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			return "/loginJuniorHighSchool";
		}
		int result = -1;
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		SignUpStudent2 stu = new SignUpStudent2();
		stu.setSfzh(sfzh);
		stu.setPassword(sfzh.substring(10, 18));
		result = signUpStudentMapper2.updatePasswordByPrimaryKey(stu);
		if (1 != result) {
			log.warn("密码更新失败");
			vo.setCode("error");
			vo.setMessage("密码更新失败");
			vo.setUrl("junior/JuniorManageSignUpInfo");
			model.addAttribute("junior", junior);
			model.addAttribute("status", "密码更新失败");
			return "junior/JuniorManageSignUpInfo";
		}
		model.addAttribute("junior", junior);
		model.addAttribute("status", "密码更新成功");
		vo.setCode("ok");
		vo.setMessage("密码更新成功");

		vo.setUrl("junior/JuniorManageSignUpInfo");

		List<SignUpStudent2> students = new ArrayList<SignUpStudent2>();
		students = juniorService.findAllSignUpStudentsByByzxdm(junior.getByzxdm());
		model.addAttribute("students", students);

		return "junior/JuniorManageSignUpInfo";

	}

	/**
	 * 根据毕业中学代码和学生身份证号查询已经报名的学生信息
	 * 
	 * @param byzxdm
	 * @param sfzh
	 * @param model
	 * @return
	 */
	@RequestMapping("doSelectSignUpStudentByByzxdmAndSfzh")
	public String selectSignUpStudentByByzxdmAndSfzh(@ModelAttribute("search_sfzh") String sfzh, Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("初级中学未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("初级中学未登录，请重新登录");
			vo.setUrl("redirect:/loginJuniorHighSchool");
			// return vo;
			return "/loginJuniorHighSchool";
		}

		if (null == sfzh || sfzh.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件指定学生身份证号");
			vo.setUrl("junior/JuniorManageSignUpInfo");
			// return vo;
		}
		List<SignUpStudent2> students = new ArrayList<SignUpStudent2>();

		Map<String, String> param = new HashMap<String, String>();
		param.put("sfzh", sfzh);
		param.put("byzxdm", junior.getByzxdm());
		students = signUpStudentMapper2.listByByzxdmAndSfzh(param);
		model.addAttribute("students", students);
		model.addAttribute("junior", junior);

		return "/junior/JuniorManageSignUpInfo";
	}

	/**
	 * 跳转到修改学生信息页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "takePhoto", method = RequestMethod.POST)
	public String takePhoto(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		if (null == session || null == junior) {
			session = null;
			log.error("用户未登录，请重新登录");
			// return "redirect:/";
			return "/loginJuniorHighSchool";
		}
		// model.addAttribute("stu", signUpStudent);
		model.addAttribute("junior", junior);
		// model.addAttribute("sfzh", sfzh);
		List<SignUpStudent2> studentlist = signUpStudentMapper2.listByByzxdm(junior.getByzxdm());
		model.addAttribute("studentlist", studentlist);

		return "/junior/takeStPhoto";
	}

	// base64字符串转化成图片
	@RequestMapping(value = "doSavePhoto", method = RequestMethod.POST)
	public String savePhoto(@RequestParam("imgData") String imgData, @RequestParam("sfzh") String sfzh,
			HttpServletResponse response, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		MiddleSchool junior = (MiddleSchool) session.getAttribute("junior");
		model.addAttribute("junior", junior);
		if (null == session || null == junior) {
			session = null;
			log.error("用户未登录，请重新登录");
			// return "redirect:/";
			return "/loginJuniorHighSchool";
		}

		// 对字节数组字符串进行Base64解码并生成图片
		if (imgData == null) {// 图像数据为空
			return "/junior/takeStPhoto";
		}
		// Base64 decoder = new Base64();
		BASE64Decoder decoder = new BASE64Decoder();
		String savePath = photoPath;

		try {

			response.setCharacterEncoding("UTF-8");

			Date day = new Date();
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			// Base64解码（好像没什么作用）
			byte[] b = decoder.decodeBuffer(imgData);
//			for (int i = 0; i < b.length; ++i) {
//				if (b[i] < 0) {// 调整异常数据
//					b[i] += 256;
//				}
//			}
			// 用正则去掉开头的"data:image/png;base64,"
			// int i = imgData.indexOf("base64,");
			// imgData = imgData.substring(23);
			// 生成jpeg图片
			if (savePath.endsWith("/")) {
				if (!savePath.endsWith(junior.getByzxdm() + "/")) {
					savePath = savePath + junior.getByzxdm() + "/";
				}

			} else {
				if (!savePath.endsWith(junior.getByzxdm())) {
					savePath = savePath + "/" + junior.getByzxdm() + "/";
				}
			}
			File photoDir = new File(savePath);
			if (!photoDir.exists()) {
				photoDir.mkdir();
			}
			String imgFilePath = savePath + sfzh + ".png";// 新生成的图片
			File file = new File(imgFilePath);
			if (file.exists()) {
				// 提醒照片文件已经存在
				System.out.println(sfzh + "的照片文件已经存在，请确认是否替换？");
				file.delete();
			}
			FileOutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();

			/**
			 * 保存拍照信息
			 */
			Photo photo = new Photo();
			photo.setSfzh(sfzh);
			photo.setTakeTime(df.format(day));
			photo.setPhotoPath(imgFilePath);
			photo.setCityId(junior.getByzxdm());

			// 不存在则插入，存在则更新
			if (null == photoMapper.getOne(sfzh)) {
				photoMapper.insertSelective(photo);
			} else {
				photoMapper.updatePasswordByPrimaryKey(photo);
			}
			response.getWriter().write("<script>alert('照片保存成功');</script>");
			return "/junior/takeStPhoto";
		} catch (Exception e) {
			log.debug(e.getMessage());
			System.out.println(e.getMessage());
			try {
				response.getWriter().write("<script>alert('照片保存失败');</script>");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return "/junior/takeStPhoto";
		}
	}

}
